package handler

import (
	"chat-box/global"
	"chat-box/initiate/dto"
	"chat-box/initiate/model"
	"chat-box/pkg"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type UserHandler struct {
}

func NweUserHandler() *UserHandler {
	return &UserHandler{}
}
func (u UserHandler) Login(c *gin.Context) {
	var logins dto.Login
	err := c.ShouldBind(&logins)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数获取失败",
		})
		return
	}
	var user model.User
	err = global.DB.Debug().Where("mobile=?", logins.Mobile).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号不存在",
		})
		return
	}
	if user.Password != logins.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "token生成失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": handler,
	})
	return
}
func (u UserHandler) List(c *gin.Context) {
	var userId dto.List
	err := c.ShouldBind(&userId)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数获取失败",
		})
		return
	}
	var friend []model.Friend
	result, _ := global.Rdb.Get(global.Ctx, "list"+strconv.Itoa(userId.UserId)).Result()
	if result == "" {
		err = global.DB.Debug().Where("user_id=?", userId.UserId).Find(&friend).Error
		if err != nil {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "联系人列表查询失败",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": friend,
		})
		marshal, _ := json.Marshal(friend)
		global.Rdb.Set(global.Ctx, "list"+strconv.Itoa(userId.UserId), marshal, time.Hour*1)
	}
}
func (u UserHandler) AddFriend(c *gin.Context) {
	var fri dto.AddFriend
	err := c.ShouldBind(&fri)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数获取失败",
		})
		return
	}
	friend := model.Friend{
		UserId:   fri.UserId,
		FriendId: fri.FriendId,
	}
	global.DB.Debug().Create(&friend)

	friends := model.Friend{
		UserId:   fri.FriendId,
		FriendId: fri.UserId,
	}
	global.DB.Debug().Create(&friends)
	var friendss []model.Friend
	global.DB.Debug().Where("user_id=?", fri.UserId).Find(&friendss)
	marshal, _ := json.Marshal(friendss)
	global.Rdb.Set(global.Ctx, "list"+strconv.Itoa(fri.UserId), marshal, time.Hour*1)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加好友成功",
	})
}
